package com.nhutcm.trackingthief;

import android.content.ComponentName;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.telephony.TelephonyManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.nhutcm.trackingthief.receiver.SecretCodeReceiver;
import com.nhutcm.trackingthief.utils.Constant;
import com.nhutcm.trackingthief.utils.PrefUtils;

public class ConfigScreen extends PreferenceActivity {

	public static final String TAG = "com.nhutcm.trackingthief.ConfigScreen";

	LinearLayout llContent;

	OnSharedPreferenceChangeListener listener;
	TelephonyManager telemamanger;
	String oldSecretCode = "";
	String oldEmail = "";

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		checkSim();

		loadConfig();

		addPreferencesFromResource(R.layout.layout_config);

		CheckBoxPreference cbb = (CheckBoxPreference) findPreference(getString(R.string.pref_allow_remove_key));
		cbb.setChecked(true);
		cbb.setEnabled(false);

		listener = new OnSharedPreferenceChangeListener() {

			@Override
			public void onSharedPreferenceChanged(SharedPreferences arg0,
					String key) {

				if (key.equals(getString(R.string.pref_hide_app_key))) {
					boolean isShow = PrefUtils.readBooleanFromPreference(
							getApplicationContext(),
							getString(R.string.pref_hide_app_key));
					if (isShow) {
						hideApp(getApplicationContext());
					} else {
						showApp(getApplicationContext());
					}
				} else if (key.equals(getString(R.string.pref_code_key))) {
					String newCode = PrefUtils.readStringFromPreference(
							getApplicationContext(),
							getString(R.string.pref_code_key));
					if (newCode.equals("")) {
						PrefUtils.saveStringToPreference(
								getApplicationContext(),
								getString(R.string.pref_code_key),
								oldSecretCode);
						Toast.makeText(getApplicationContext(),
								getString(R.string.empty_code),
								Toast.LENGTH_SHORT).show();
					} else {

						String code = PrefUtils.readStringFromPreference(
								getApplicationContext(),
								getString(R.string.pref_code_key));

						if (code.equals("")) {
							code = Constant.DEDAULT_SECRECT_CODE;
						}

						/**
						 * unregisterReceiver
						 */
						if (Constant.currentReceiver != null) {
							getApplicationContext().unregisterReceiver(
									Constant.currentReceiver);
						}

						IntentFilter i = new IntentFilter(
								"android.provider.Telephony.SECRET_CODE");
						i.addDataScheme("android_secret_code");
						i.addDataAuthority(code, null);

						SecretCodeReceiver receiver = new SecretCodeReceiver();
						getApplicationContext().registerReceiver(receiver, i);

						Constant.currentReceiver = receiver;
					}

				} else if (key
						.equals(getString(R.string.pref_allow_remove_key))) {
				} else if (key
						.equals(getString(R.string.pref_phone_update_state_key))) {
					String simSerialNumber = telemamanger.getSimSerialNumber();
					PrefUtils.saveStringToPreference(getApplicationContext(),
							getString(R.string.pref_phone_serial_number),
							simSerialNumber);

					PrefUtils.saveStringToPreference(getApplicationContext(),
							getString(R.string.phone_state), "1");

				} else if (key.equals(getString(R.string.pref_email_key))) {
					String newEmail = PrefUtils.readStringFromPreference(
							getApplicationContext(),
							getString(R.string.pref_email_key));
					if (newEmail.equals("")) {
						Toast.makeText(getApplicationContext(),
								getString(R.string.empty_email),
								Toast.LENGTH_SHORT).show();
						PrefUtils.saveStringToPreference(
								getApplicationContext(),
								getString(R.string.pref_email_key), oldEmail);
					}
				}

			}
		};

		SharedPreferences prefs = getSharedPreferences(getPackageName()
				+ "_preferences", MODE_PRIVATE);
		prefs.registerOnSharedPreferenceChangeListener(listener);
	}

	/*
	 * private void loadLanguage() { String langValue =
	 * PrefUtils.readFromPreference( getApplicationContext(),
	 * getString(R.string.pref_lang_key));
	 * 
	 * if (langValue == null || langValue.equals("")) {
	 * PrefUtils.saveToPreference(getApplicationContext(),
	 * getString(R.string.pref_lang_key), "1"); }
	 * 
	 * }
	 */

	void checkSim() {
		String simSerialNumber = telemamanger.getSimSerialNumber();
		String configSerial = PrefUtils.readStringFromPreference(
				getApplicationContext(),
				getString(R.string.pref_phone_serial_number));

		if (simSerialNumber.equals(configSerial)) {

			PrefUtils.saveBooleanToPreference(getApplicationContext(),
					getString(R.string.pref_phone_update_state_key), true);
		} else {

			PrefUtils.saveBooleanToPreference(getApplicationContext(),
					getString(R.string.pref_phone_update_state_key), false);
		}
	}

	private void loadConfig() {
		oldSecretCode = PrefUtils.readStringFromPreference(
				getApplicationContext(), getString(R.string.pref_code_key));

		oldEmail = PrefUtils.readStringFromPreference(getApplicationContext(),
				getString(R.string.pref_email_key));
	}

	void hideApp(Context context) {
		PackageManager p = getPackageManager();
		ComponentName componentName = new ComponentName(context,
				com.nhutcm.trackingthief.HomeScreen.class);
		p.setComponentEnabledSetting(componentName,
				PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
				PackageManager.DONT_KILL_APP);
	}

	void showApp(Context context) {
		PackageManager p = getPackageManager();
		ComponentName componentName = new ComponentName(context,
				com.nhutcm.trackingthief.HomeScreen.class);
		p.setComponentEnabledSetting(componentName,
				PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
				PackageManager.DONT_KILL_APP);
	}
}
